'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import AppHeader from '@/components/ui/app-header';
import { 
  ChevronLeftIcon,
  TagIcon,
  PlusIcon,
  XMarkIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/24/outline';

// 任务类型定义
interface Task {
  id: string;
  title: string;
  description: string | null;
  status: string;
  priority: string;
  assignee: {
    id: string;
    name: string;
    image?: string;  // 与API返回匹配，使用image而不是avatar
    email?: string;
  } | null;
  assigneeId?: string; // 添加assigneeId字段
  dueDate: string | null;
  projectId: string;
  tags?: string[];  // 添加可选标记
  createdAt: string;
  updatedAt: string;
}

export default function EditTaskPage() {
  const router = useRouter();
  const params = useParams();
  const taskId = params.id as string;
  
  const [formData, setFormData] = useState<Partial<Task>>({
    title: '',
    description: '',
    status: 'TODO', // 使用大写状态，与API一致
    priority: 'MEDIUM', // 使用大写优先级，与API一致
    dueDate: '',
    projectId: '',
  });
  
  const [tags, setTags] = useState<string[]>([]);
  const [tagInput, setTagInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [fetchLoading, setFetchLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [fetchError, setFetchError] = useState<string | null>(null);

  // 获取任务数据
  useEffect(() => {
    const fetchTask = async () => {
      setFetchLoading(true);
      setFetchError(null);
      try {
        const response = await fetch(`/api/task?id=${taskId}`);
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.success) {
          const task = data.data;
          setFormData({
            title: task.title,
            description: task.description || '',
            status: task.status,
            priority: task.priority,
            dueDate: task.dueDate ? task.dueDate.split('T')[0] : '', // 格式化日期
            projectId: task.projectId,
            assigneeId: task.assignee?.id,
          });
          setTags(task.tags || []);
        } else {
          throw new Error(data.message || '获取任务失败');
        }
      } catch (err: any) {
        console.error('获取任务详情失败:', err);
        setFetchError(err.message || '获取任务详情失败');
      } finally {
        setFetchLoading(false);
      }
    };
    
    if (taskId) {
      fetchTask();
    }
  }, [taskId]);

  // 处理表单字段变更
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 处理标签添加
  const handleAddTag = () => {
    if (tagInput.trim() && !tags.includes(tagInput.trim())) {
      setTags(prev => [...prev, tagInput.trim()]);
      setTagInput('');
    }
  };

  // 处理标签删除
  const handleRemoveTag = (tagToRemove: string) => {
    setTags(prev => prev.filter(tag => tag !== tagToRemove));
  };

  // 处理标签输入框按键事件
  const handleTagKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddTag();
    }
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      // 确保状态和优先级使用大写格式
      const formattedData = {
        ...formData,
        status: formData.status?.toUpperCase(),
        priority: formData.priority?.toUpperCase(),
      };
      
      console.log("提交的数据:", formattedData); // 调试用

      const response = await fetch(`/api/task?id=${taskId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formattedData,
          tags,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || `请求失败: ${response.status}`);
      }

      const data = await response.json();
      if (data.success) {
        // 更新成功，跳转到任务详情页
        router.push(`/task/${taskId}`);
      } else {
        throw new Error(data.message || '更新任务失败');
      }
    } catch (err: any) {
      console.error('更新任务失败:', err);
      setError(err.message || '更新任务失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <div className="mb-6">
          <button
            type="button"
            onClick={() => router.back()}
            className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 focus:outline-none"
          >
            <ChevronLeftIcon className="h-5 w-5 mr-1" />
            返回
          </button>
        </div>

        <AppHeader
          title="编辑任务"
          subtitle={`编辑任务 #${taskId}`}
        />

        {fetchLoading ? (
          <div className="mt-6 flex justify-center py-12">
            <div className="animate-pulse text-gray-500">加载任务中...</div>
          </div>
        ) : fetchError ? (
          <div className="mt-6 bg-red-50 p-4 rounded-md">
            <div className="flex">
              <div className="flex-shrink-0">
                <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">加载任务时出错</h3>
                <div className="mt-2 text-sm text-red-700">
                  <p>{fetchError}</p>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="mt-6 bg-white shadow rounded-lg overflow-hidden">
            <form onSubmit={handleSubmit} className="p-6">
              {error && (
                <div className="mb-6 bg-red-50 p-4 rounded-md">
                  <div className="flex">
                    <div className="flex-shrink-0">
                      <XMarkIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
                    </div>
                    <div className="ml-3">
                      <h3 className="text-sm font-medium text-red-800">更新任务时出错</h3>
                      <div className="mt-2 text-sm text-red-700">
                        <p>{error}</p>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              <div className="space-y-6">
                {/* 任务标题 */}
                <div>
                  <label htmlFor="title" className="block text-sm font-medium text-gray-700">
                    任务标题 <span className="text-red-500">*</span>
                  </label>
                  <div className="mt-1">
                    <input
                      type="text"
                      name="title"
                      id="title"
                      required
                      value={formData.title || ''}
                      onChange={handleChange}
                      className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      placeholder="输入任务标题"
                    />
                  </div>
                </div>

                {/* 任务描述 */}
                <div>
                  <label htmlFor="description" className="block text-sm font-medium text-gray-700">
                    任务描述
                  </label>
                  <div className="mt-1">
                    <textarea
                      name="description"
                      id="description"
                      rows={4}
                      value={formData.description || ''}
                      onChange={handleChange}
                      className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      placeholder="详细描述任务内容、要求等"
                    />
                  </div>
                </div>

                {/* 项目ID */}
                <div>
                  <label htmlFor="projectId" className="block text-sm font-medium text-gray-700">
                    所属项目 <span className="text-red-500">*</span>
                  </label>
                  <div className="mt-1">
                    <input
                      type="text"
                      name="projectId"
                      id="projectId"
                      required
                      value={formData.projectId || ''}
                      onChange={handleChange}
                      className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      placeholder="输入项目ID"
                    />
                  </div>
                </div>

                {/* 任务状态 */}
                <div>
                  <label htmlFor="status" className="block text-sm font-medium text-gray-700">
                    任务状态
                  </label>
                  <div className="mt-1">
                    <select
                      id="status"
                      name="status"
                      value={formData.status || 'TODO'}
                      onChange={handleChange}
                      className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                    >
                      <option value="TODO">待处理</option>
                      <option value="IN_PROGRESS">进行中</option>
                      <option value="REVIEW">审核中</option>
                      <option value="DONE">已完成</option>
                    </select>
                  </div>
                </div>

                {/* 优先级 */}
                <div>
                  <label htmlFor="priority" className="block text-sm font-medium text-gray-700">
                    优先级
                  </label>
                  <div className="mt-1">
                    <select
                      id="priority"
                      name="priority"
                      value={formData.priority || 'MEDIUM'}
                      onChange={handleChange}
                      className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                    >
                      <option value="LOW">低</option>
                      <option value="MEDIUM">中</option>
                      <option value="HIGH">高</option>
                      <option value="URGENT">紧急</option>
                    </select>
                  </div>
                </div>

                {/* 截止日期 */}
                <div>
                  <label htmlFor="dueDate" className="block text-sm font-medium text-gray-700">
                    截止日期
                  </label>
                  <div className="mt-1">
                    <input
                      type="date"
                      name="dueDate"
                      id="dueDate"
                      value={formData.dueDate || ''}
                      onChange={handleChange}
                      className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                    />
                  </div>
                </div>

                {/* 标签 */}
                <div>
                  <label htmlFor="tags" className="block text-sm font-medium text-gray-700">
                    标签
                  </label>
                  <div className="mt-1 flex rounded-md shadow-sm">
                    <div className="relative flex flex-grow items-stretch focus-within:z-10">
                      <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                        <TagIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                      </div>
                      <input
                        type="text"
                        id="tags"
                        value={tagInput}
                        onChange={(e) => setTagInput(e.target.value)}
                        onKeyDown={handleTagKeyDown}
                        className="block w-full rounded-none rounded-l-md border-gray-300 pl-10 focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                        placeholder="添加标签"
                      />
                    </div>
                    <button
                      type="button"
                      onClick={handleAddTag}
                      className="relative -ml-px inline-flex items-center space-x-2 rounded-r-md border border-gray-300 bg-gray-50 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                    >
                      <PlusIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                      <span>添加</span>
                    </button>
                  </div>

                  {tags.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-2">
                      {tags.map((tag) => (
                        <span
                          key={tag}
                          className="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800"
                        >
                          {tag}
                          <button
                            type="button"
                            onClick={() => handleRemoveTag(tag)}
                            className="ml-1 inline-flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full text-blue-400 hover:bg-blue-200 hover:text-blue-500 focus:bg-blue-500 focus:text-white focus:outline-none"
                          >
                            <span className="sr-only">移除标签 {tag}</span>
                            <XMarkIcon className="h-3 w-3" aria-hidden="true" />
                          </button>
                        </span>
                      ))}
                    </div>
                  )}
                </div>

                {/* 提交按钮 */}
                <div className="flex justify-end pt-5">
                  <button
                    type="button"
                    onClick={() => router.back()}
                    className="rounded-md border border-gray-300 bg-white py-2 px-4 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    disabled={loading || !formData.title || !formData.projectId}
                    className="ml-3 inline-flex justify-center rounded-md border border-transparent bg-[var(--primary-color)] py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-[var(--primary-hover)] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
                  >
                    {loading ? '保存中...' : '保存更改'}
                  </button>
                </div>
              </div>
            </form>
          </div>
        )}
      </main>
    </div>
  );
} 